import AMapLoader from '@amap/amap-jsapi-loader'
import { message } from 'ant-design-vue'

// 高德地图配置
const MAP_CONFIG = {
  key: import.meta.env.VITE_AMAP_KEY, // Web端(JS API)密钥
  version: '2.0',
  plugins: [
    'AMap.PlaceSearch', 
    'AMap.Geocoder'
  ],
  // 安全密钥配置
  securityJsCode: import.meta.env.VITE_AMAP_SECURITY_CODE, // Web端安全密钥
  Loca: {
    version: '2.0'
  }
}

// 地图实例缓存
let mapInstanceCache: any = null
let AMapCache: any = null

// 位置信息接口
export interface LocationInfo {
  longitude: number
  latitude: number
  address: string
  name?: string
  district?: string
  city?: string
  province?: string
  adcode?: string
  citycode?: string
}

/**
 * 检查API密钥配置
 */
const checkApiKeys = () => {
  const apiKey = import.meta.env.VITE_AMAP_KEY
  const securityCode = import.meta.env.VITE_AMAP_SECURITY_CODE
  
  if (!apiKey) {
    const errorMsg = '高德地图API密钥未配置！请在.env文件中设置 VITE_AMAP_KEY（Web端JS API密钥）'
    message.error(errorMsg)
    throw new Error(errorMsg)
  }
  
  if (!securityCode) {
    const errorMsg = '高德地图安全密钥未配置！请在.env文件中设置 VITE_AMAP_SECURITY_CODE（Web端安全密钥）'
    message.error(errorMsg)
    throw new Error(errorMsg)
  }
}

/**
 * 初始化高德地图
 */
export const initAMap = async (): Promise<any> => {
  if (AMapCache) {
    return AMapCache
  }

  // 检查API密钥配置
  checkApiKeys()

  // 设置安全配置（必须在AMapLoader.load之前设置）
  if (typeof window !== 'undefined') {
    ;(window as any)._AMapSecurityConfig = {
      securityJsCode: MAP_CONFIG.securityJsCode
    }
  }

  try {
    AMapCache = await AMapLoader.load(MAP_CONFIG)
    return AMapCache
  } catch (error) {
    console.error('地图加载失败:', error)
    
    // 根据错误类型提供更具体的错误信息
    const errorMessage = error instanceof Error ? error.message : String(error)
    
    if (errorMessage.includes('USERKEY_PLAT_NOMATCH')) {
      message.error('API密钥平台不匹配！请确保在高德控制台勾选了"Web端(JS API)"服务')
    } else if (errorMessage.includes('INVALID_USER_KEY')) {
      message.error('API密钥无效！请检查VITE_AMAP_KEY配置是否正确')
    } else if (errorMessage.includes('DAILY_QUERY_OVER_LIMIT')) {
      message.error('API调用次数超限！请检查您的配额')
    } else {
      message.error('地图服务初始化失败，请检查网络连接和API密钥配置')
    }
    
    throw error
  }
}

/**
 * 创建地图实例
 */
export const createMapInstance = async (
  containerId: string,
  options: {
    center?: [number, number]
    zoom?: number
    viewMode?: string
  } = {}
): Promise<any> => {
  const AMap = await initAMap()
  
  const defaultOptions = {
    center: [113.264435, 23.129162], // 默认中心点（广州市）
    zoom: 13,
    viewMode: '3D',
    mapStyle: 'amap://styles/whitesmoke', // 使用更清爽的地图样式
    features: ['bg', 'point', 'road', 'building'], // 显示背景、兴趣点、道路、建筑物
    ...options
  }

  const map = new AMap.Map(containerId, defaultOptions)
  mapInstanceCache = map
  
  return map
}

/**
 * 创建增强版地图位置选择器
 * @param containerId 地图容器ID
 * @param onLocationSelect 位置选择回调
 * @param onConfirm 确认选择回调
 * @param initialLocation 初始位置
 */
export const createEnhancedLocationPicker = async (
  containerId: string,
  onLocationSelect?: (location: LocationInfo) => void,
  onConfirm?: (location: LocationInfo) => void,
  initialLocation?: { longitude: number; latitude: number }
): Promise<{ 
  map: any; 
  marker: any; 
  searchNearby: (keyword: string) => void;
  setLocation: (lng: number, lat: number) => void;
  getCurrentLocation: () => LocationInfo | null;
  destroy: () => void;
}> => {
  const AMap = await initAMap()
  
  let currentLocation: LocationInfo | null = null
  let infoWindow: any = null
  let searchMarkers: any[] = [] // 搜索结果标记
  const confirmButton: HTMLElement | null = null
  
  // 创建地图
  const map = await createMapInstance(containerId, {
    center: initialLocation ? [initialLocation.longitude, initialLocation.latitude] : [113.264435, 23.129162],
    zoom: 15
  })

  // 创建主标记点（可拖拽）
  const mainMarker = new AMap.Marker({
    position: map.getCenter(),
    draggable: true,
    cursor: 'move',
    icon: new AMap.Icon({
      size: new AMap.Size(32, 44),
      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
      imageOffset: new AMap.Pixel(-16, -44)
    }),
    title: '选中的位置',
    zIndex: 100
  })
  map.add(mainMarker)

  // 创建地理编码服务
  const geocoder = new AMap.Geocoder({
    radius: 1000,
    extensions: 'all'
  })

  // 创建POI搜索服务
  const placeSearch = new AMap.PlaceSearch({
    pageSize: 10,
    pageIndex: 1,
    city: '全国',
    citylimit: false,
    autoFitView: false
  })

  // 创建信息窗体
  const createInfoWindow = (location: LocationInfo, isPoi: boolean = false) => {
    const content = `
      <div style="padding: 10px; min-width: 200px;">
        <div style="font-weight: bold; margin-bottom: 8px; color: #1890ff;">
          ${location.name || '选中位置'}
        </div>
        <div style="margin-bottom: 5px; color: #666;">
          📍 ${location.address}
        </div>
        <div style="margin-bottom: 5px; color: #888; font-size: 12px;">
          经度: ${location.longitude.toFixed(6)}
        </div>
        <div style="margin-bottom: 10px; color: #888; font-size: 12px;">
          纬度: ${location.latitude.toFixed(6)}
        </div>
        ${isPoi ? 
          `<button id="selectPoiBtn" style="background: #1890ff; color: white; border: none; padding: 5px 15px; border-radius: 4px; cursor: pointer;">选择此位置</button>` :
          `<button id="confirmLocationBtn" style="background: #52c41a; color: white; border: none; padding: 5px 15px; border-radius: 4px; cursor: pointer;">确认选择</button>`
        }
      </div>
    `
    
    if (infoWindow) {
      infoWindow.close()
    }
    
    infoWindow = new AMap.InfoWindow({
      content,
      offset: new AMap.Pixel(0, -40),
      closeWhenClickMap: true
    })
    
    return infoWindow
  }

  // 更新位置信息
  const updateLocation = async (lng: number, lat: number, name?: string) => {
    try {
      geocoder.getAddress([lng, lat], (status: string, result: any) => {
        if (status === 'complete' && result.regeocode) {
          const regeocode = result.regeocode
          const location: LocationInfo = {
            longitude: lng,
            latitude: lat,
            address: regeocode.formattedAddress,
            name: name || regeocode.addressComponent.building || regeocode.addressComponent.poi || '',
            district: regeocode.addressComponent.district,
            city: regeocode.addressComponent.city,
            province: regeocode.addressComponent.province,
            adcode: regeocode.addressComponent.adcode,
            citycode: regeocode.addressComponent.citycode
          }
          
          currentLocation = location
          onLocationSelect?.(location)
          
          // 创建信息窗体
          const infoWin = createInfoWindow(location)
          infoWin.open(map, [lng, lat])
          
          // 绑定确认按钮事件
          setTimeout(() => {
            const confirmBtn = document.getElementById('confirmLocationBtn')
            if (confirmBtn) {
              confirmBtn.onclick = () => {
                onConfirm?.(location)
                infoWin.close()
                message.success(`已选择位置：${location.name || location.address}`)
              }
            }
          }, 100)
        }
      })
    } catch (error) {
      console.error('获取地址信息失败:', error)
    }
  }

  // 清除搜索结果标记
  const clearSearchMarkers = () => {
    searchMarkers.forEach(marker => map.remove(marker))
    searchMarkers = []
  }

  // POI搜索功能
  const searchNearby = (keyword: string) => {
    if (!keyword.trim()) {
      message.warning('请输入搜索关键词')
      return
    }
    
    clearSearchMarkers()
    
    // 添加搜索加载提示
    const loadingMessage = message.loading('正在搜索地点...', 0)
    
    try {
      placeSearch.search(keyword, (status: string, result: any) => {
        // 关闭加载提示
        loadingMessage()
        
        if (status === 'complete') {
          if (result && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
            const pois = result.poiList.pois.slice(0, 8) // 最多显示8个结果，减少渲染压力
            
            pois.forEach((poi: any, index: number) => {
              if (poi.location && poi.location.lng && poi.location.lat) {
                try {
                  // 创建POI标记（红色）
                  const poiMarker = new AMap.Marker({
                    position: [poi.location.lng, poi.location.lat],
                    icon: new AMap.Icon({
                      size: new AMap.Size(25, 35),
                      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
                      imageOffset: new AMap.Pixel(-12, -35)
                    }),
                    title: poi.name,
                    zIndex: 50
                  })
                  
                  // POI点击事件
                  poiMarker.on('click', () => {
                    const location: LocationInfo = {
                      longitude: poi.location.lng,
                      latitude: poi.location.lat,
                      address: poi.address || `${poi.pname || ''}${poi.cityname || ''}${poi.adname || ''}`,
                      name: poi.name,
                      district: poi.adname,
                      city: poi.cityname,
                      province: poi.pname
                    }
                    
                    // 创建POI信息窗体
                    const poiInfoWindow = createInfoWindow(location, true)
                    poiInfoWindow.open(map, [poi.location.lng, poi.location.lat])
                    
                    // 绑定选择按钮事件
                    setTimeout(() => {
                      const selectBtn = document.getElementById('selectPoiBtn')
                      if (selectBtn) {
                        selectBtn.onclick = () => {
                          // 移动主标记到POI位置
                          mainMarker.setPosition([poi.location.lng, poi.location.lat])
                          map.setCenter([poi.location.lng, poi.location.lat])
                          
                          // 更新位置信息
                          currentLocation = location
                          onLocationSelect?.(location)
                          
                          poiInfoWindow.close()
                          message.success(`已选择：${poi.name}`)
                          
                          // 清除其他POI标记
                          clearSearchMarkers()
                        }
                      }
                    }, 100)
                  })
                  
                  map.add(poiMarker)
                  searchMarkers.push(poiMarker)
                } catch (markerError) {
                  console.error(`创建POI标记失败 ${poi.name}:`, markerError)
                }
              } else {
                console.warn(`POI ${poi.name} 缺少位置信息`)
              }
            })
            
            // 自动调整视野
            if (pois.length > 0 && pois[0] && pois[0].location) {
              try {
                map.setCenter([pois[0].location.lng, pois[0].location.lat])
                
                if (pois.length === 1) {
                  map.setZoom(16)
                } else {
                  // 多个结果时，调整视野包含所有结果
                  const bounds = new AMap.Bounds()
                  pois.forEach((poi: any) => {
                    if (poi.location && poi.location.lng && poi.location.lat) {
                      bounds.extend([poi.location.lng, poi.location.lat])
                    }
                  })
                  if (!bounds.isEmpty()) {
                    map.setBounds(bounds, false, [20, 20, 20, 20])
                  }
                }
              } catch (viewError) {
                console.error('调整地图视野失败:', viewError)
              }
            }
            
            message.success(`找到 ${pois.length} 个相关地点，点击红色标记选择`)
          } else {
            message.warning('未找到相关地点，请尝试其他关键词')
          }
        } else if (status === 'no_data') {
          message.warning('未找到相关地点，请尝试其他关键词')
        } else if (status === 'error') {
          console.error('搜索出错:', result)
          // 根据具体错误码提供更详细的错误信息
          const errorInfo = result?.info || '未知错误'
          
          if (errorInfo.includes('USERKEY_PLAT_NOMATCH')) {
            message.error('API密钥平台不匹配！请确保在高德控制台勾选了"Web端(JS API)"和"Web服务"')
          } else if (errorInfo.includes('INVALID_USER_KEY')) {
            message.error('API密钥无效！请检查密钥配置')
          } else if (errorInfo.includes('DAILY_QUERY_OVER_LIMIT')) {
            message.error('API调用次数超限！请检查您的配额')
          } else if (errorInfo.includes('QPS_OVER_LIMIT')) {
            message.error('请求频率过高，请稍后再试')
          } else {
            message.error(`搜索失败: ${errorInfo}`)
          }
        } else {
          console.error('未知搜索状态:', status, result)
          message.error('搜索服务异常，请稍后重试')
        }
      })
    } catch (searchError) {
      loadingMessage()
      console.error('搜索请求失败:', searchError)
      message.error('搜索功能异常，请刷新页面重试')
    }
  }

  // 地图点击事件
  map.on('click', (e: any) => {
    const lng = e.lnglat.lng
    const lat = e.lnglat.lat
    
    // 移动标记到点击位置
    mainMarker.setPosition([lng, lat])
    
    // 清除搜索结果
    clearSearchMarkers()
    
    // 更新位置信息
    updateLocation(lng, lat)
  })

  // 标记拖拽事件
  mainMarker.on('dragend', () => {
    const position = mainMarker.getPosition()
    updateLocation(position.lng, position.lat)
  })

  // 设置位置
  const setLocation = (lng: number, lat: number) => {
    mainMarker.setPosition([lng, lat])
    map.setCenter([lng, lat])
    updateLocation(lng, lat)
  }

  // 获取当前位置
  const getCurrentLocation = () => currentLocation

  // 销毁地图
  const destroy = () => {
    clearSearchMarkers()
    if (infoWindow) {
      infoWindow.close()
    }
    if (map) {
      map.destroy()
    }
  }

  // 初始化时更新位置信息
  if (initialLocation) {
    updateLocation(initialLocation.longitude, initialLocation.latitude)
  } else {
    updateLocation(map.getCenter().lng, map.getCenter().lat)
  }

  return {
    map,
    marker: mainMarker,
    searchNearby,
    setLocation,
    getCurrentLocation,
    destroy
  }
}

/**
 * 创建只读地图（用于展示）
 */
export const createReadonlyMap = async (
  containerId: string,
  location: { longitude: number; latitude: number; title?: string }
): Promise<any> => {
  const AMap = await initAMap()
  
  const map = await createMapInstance(containerId, {
    center: [location.longitude, location.latitude],
    zoom: 16
  })

  // 添加标记点
  const marker = new AMap.Marker({
    position: [location.longitude, location.latitude],
    icon: new AMap.Icon({
      size: new AMap.Size(32, 44),
      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
      imageOffset: new AMap.Pixel(-16, -44)
    }),
    title: location.title || '学校位置'
  })
  map.add(marker)

  // 添加信息窗体
  if (location.title) {
    const infoWindow = new AMap.InfoWindow({
      content: `
        <div style="padding: 10px;">
          <div style="font-weight: bold; color: #1890ff;">${location.title}</div>
          <div style="margin-top: 5px; color: #666; font-size: 12px;">
            经纬度: ${location.longitude.toFixed(6)}, ${location.latitude.toFixed(6)}
          </div>
        </div>
      `,
      offset: new AMap.Pixel(0, -40)
    })
    
    marker.on('click', () => {
      infoWindow.open(map, marker.getPosition())
    })
    
    // 默认显示信息窗体
    infoWindow.open(map, marker.getPosition())
  }

  return map
}

/**
 * 销毁地图实例
 */
export const destroyMap = () => {
  if (mapInstanceCache) {
    mapInstanceCache.destroy()
    mapInstanceCache = null
  }
} 